<template>
	<section ref="emp">
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="query">
				<el-form-item>
					<el-input v-model="query.keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="search">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

    <!--列表-->
    <el-table :data="pageInfo.rows" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="username" label="名字" width="120">
      </el-table-column>
      <el-table-column prop="password" label="密码" width="150">
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="150">
      </el-table-column>
      <el-table-column prop="headImage" label="头像" width="100">

          <template slot-scope="scope">
            <el-avatar  shape="circle" :size="50" :src="scope.row.headImage"></el-avatar>
          </template>


      </el-table-column>
      <el-table-column prop="age" label="年龄" width="50">
      </el-table-column>
      <el-table-column prop="dept.name" label="父部门" min-width="80">
      </el-table-column>

      <el-table-column label="操作" width="350">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
          <el-button type="primary" size="small" @click="handelRole(scope.$index, scope.row)">设置角色</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
<!--      <el-pagination-->
<!--          layout="total, prev, pager, next"-->
<!--          @current-change="handleCurrentChange"-->
<!--          :page-size="10"-->
<!--          :total="pageInfo.total"-->
<!--          style="float:right;">-->
<!--      </el-pagination>-->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="query.currentPage"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="query.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total" style="float:right;">
      </el-pagination>
    </el-col>


		<!--新增界面-->
		<el-dialog title="新增" :visible.sync="addFormVisible" :close-on-click-modal="false">
			<el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
				<el-form-item label="姓名" prop="username">
					<el-input v-model="addForm.username" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="密码"  prop="username">
          <el-input v-model="addForm.password" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" >
          <el-input v-model="addForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-upload
            class="avatar-uploader"
            action="https://jsonplaceholder.typicode.com/posts/"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <el-form-item label="年龄"  prop="username">
          <el-input v-model="addForm.age" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="所在部门">
          <el-select v-model="addForm.dept" clearable value-key="id" placeholder="请选择" @clear="()=>{addForm.dept={id:null,name:''}}">
            <!--下拉选项
              :key=""  //唯一标识
              :label 选择之后展示到选择框中的值
              :value 选中之后绑定给模型层的值  如果要绑定对象给模型层 有一个大坑
                 必须要写  value-key="id"
            -->
            <el-option
                v-for="item in depts"
                :key="item.id"
                :label="item.name"
                :value="item">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.intro}}</span>
            </el-option>
          </el-select>
        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>



    <el-dialog title="设置角色" :visible.sync="setempVisible" :close-on-click-modal="false">
      <el-form :model="EmpRole" label-width="80px" ref="saveForm">
        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChangeemp">全选</el-checkbox>
        <div style="margin: 15px 0;"></div>
        <el-checkbox-group v-model="EmpRole.roleid" @change="handleCheckemp">
          <el-checkbox v-for="(role,index) in roleTree" :label="role.id" :key="role.id">{{role.name}}</el-checkbox>
        </el-checkbox-group>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="setempVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveRoleemp" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>
	</section>
</template>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from '../../api/api';

	export default {
		data() {
			return {
        employees:[],
        depts:[],
        deptTree:[],
        // emp:[],
        // dep:[],

				filters: {
					name: ''
				},
        pageInfo:{
          total:0,
          rows:[]
        },
        query:{
          currentPage:1,
          pageSize:10,
          keyword:""
        },
				users: [],
				listLoading: false,
				sels: [],//列表选中列
        imageUrl: "",


				addFormVisible: false,//新增界面是否显示
				addLoading: false,
				addFormRules: {
					username: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},
				//新增界面数据
				addForm: {
          id:null,
          username: "",
          password:"",
          email:"",
          headImage:"",
          age:"",
          dept:{
            id:null,
            name:""
          },

        },
        EmpRole:{
          empid:null,
          roleid:[],  // 存放的是当前被勾选中的权限,包括一级权限和二级权限
        },
        allrole:[],
        roleTree:[],
        setempVisible:false,
        isIndeterminate:false,    // 用来控制全选框的状态
        checkAll:false,  // 控制全选框是否勾选中
			}
		},
		methods: {

      saveRoleemp(){
        this.$http.post("/emp/saverole",this.EmpRole)
            .then(result => {
              result = result.data;
              if(result.success){
                this.$message({message: '设置成功!', type: 'success'});
                // 关闭弹框
                this.setempVisible = false;
              }else{
                this.$message({message: result.message, type: 'error'});
              }
            })

      },

      handleCheckAllChangeemp(val){
        this.EmpRole.roleid = val ? this.allrole : [];
        this.isIndeterminate = false;
      },

      handleCheckemp(value) { // 多选框
        let checkedCount = value.length;
        this.checkAll = checkedCount === this.roleTree.length;
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.roleTree.length;
      },

      handelRole(index,row){
        this.setempVisible = true;
        this.getRoleTree();
        this.getAllRoleid();
        this.EmpRole.empid = row.id;
        console.log("-----当前行id")
        console.log(row.id)
        this.getroleid(row.id)
      },
      getAllRoleid(){
        this.$http.get("/emp/ids")
            .then(result => {
              result = result.data;
              console.log("===所有的角色id===")
              console.log(result)
              if(result.success){
                console.log(result.data)
                // result.resultObj 后端返回的所有的权限sn
                this.allrole = result.data;
              }
            })
      },

      getRoleTree(){
        this.$http.get("/emp/tree")
            .then(result => {
              result = result.data;
              console.log("-----角色树-----")
              console.log(result)
              if(result.success){
                this.roleTree = result.data;
              }
            })
      },
      getroleid(empid){
    this.$http.get("/emp/getroleemp/"+empid)
        .then(res =>{
          res =res.data;
          console.log("====回显时需要的角色id====")
          console.log(res)
          if(res.success){
            this.EmpRole.roleid = res.data;
          }
        })
      },




      handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },


		  getDeptTree(){
        this.$http.get("/dept/tree")
            .then(res =>{
              res=res.data;
              console.log(res.data)
              if (res.success){
                this.deptTree=res.data;
              }
            })
            .catch(res =>{


            })
      },

		  getalldepts(){
        this.$http.get("/dept")
            .then(res =>{
              res=res.data;
              console.log(res.data)
              if (res.success){
                this.depts=res.data;
              }
            })
            .catch(res =>{


            })

      },


		  search(){
        this.query.currentPage = 1;
        this.getEmployee()
      },

      handleCurrentChange(val) {
        this.query.currentPage = val;
        this.getEmployee()
      },

      handleSizeChange(val){
        this.query.pageSize=val;
        this.getEmployee()
      },

      getEmployee(){
        this.$http.post("/emp",this.query)
            .then(result => {
              console.log(result);
              result = result.data;
              console.log(result)
              this.pageInfo = result.data;
            }).catch(result => {
          this.$message({ message: '员工分页查询失败',type: 'error'});
        })
      },

			//删除  index:当前数据的行号    row:当前行数据
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?','提示',{
					type: 'warning'
				}).then(() => {
					this.listLoading = true;  //加载框 true-加载

          let id=row.id;
          this.$http.delete("/emp/"+id).then(res =>{
            this.listLoading=false;
            res=res.data;
            if(res.success){
              this.$message({message: '删除成功', type: 'success'});
            }else {
              this.$message({message:res.message, type: 'error'});
            }
            this.query.currentPage=1
            this.getEmployee()
          })

				}).catch(() => {
              this.$message('删除操作已取消')
				});
			},
			//显示编辑界面
      handleEdit: function (index,row) {
        this.addFormVisible = true;
        //将当前对象赋值给addform  回显
        this.addForm=Object.assign({},row);
        this.getalldepts();
        if(!row.dept){
          this.addForm.dept={
            id:null,
            name:""
          };

        }

        // 联级下拉框 数据回显 需要处理dept.id


      },
			//显示新增界面
			handleAdd: function () {
				this.addFormVisible = true;
				this.getalldepts();
				this.addForm = {
          id:null,
          username: "",
          password:"",
          email:"",
          headImage:"",
          age:"",
          dept:{
            id:null,
            name:""
          },
				};
			},

			//新增
			addSubmit: function () {
				this.$refs.addForm.validate((valid) => {
					if (valid) {
              this.$confirm('确定提交？','提示',{}).then(() =>{
                 this.addLoading=true;
                 let para = Object.assign({},this.addForm);


                  this.$http.put("/emp",para).then(res =>{
                     res=res.data;
                     this.addLoading=false;
                     if(res.success){
                       this.$message({message: '保存成功', type: 'success'});
                       this.query.currentPage=1;
                       this.getEmployee();
                       this.addFormVisible=false;
                     }else {
                       this.$message({message: res.message, type: 'error'});
                     }
                  }).catch(res =>{
                    this.$message({message: '网络错误', type: 'error'});
                    this.addLoading=false
                  })
              })
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id)
        console.log(ids)
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					this.$http.patch("/emp",ids).then(res =>{
					  res= res.data;
					  if(res.success){
              this.$message({message: '删除成功', type: 'success'});
              this.listLoading=false;
              this.query.currentPage=1;
              this.getEmployee()
					  }else {
              this.$message({message: res.message, type: 'error'});
            }
          })


				}).catch(() => {
          this.$message({message: '取消删除', type: 'error'});
				});
			}
		},


		mounted() {
      this.getEmployee()
		}
	}

</script>

<style scoped>

</style>